package com.cuanbo.dualscreenteachzhu.utils;

import android.content.Context;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.util.Log;

import androidx.annotation.NonNull;

import java.util.HashMap;
import java.util.Iterator;

import cn.wch.uartlib.WCHUARTManager;
import cn.wch.uartlib.callback.IUsbStateChange;
import cn.wch.uartlib.exception.ChipException;
import cn.wch.uartlib.exception.NoPermissionException;

public class UsbTouchHepler {
    private Context context;
    private UsbManager usbManager;
    private UsbDevice usbDevice;
    private int screenWidth=1920;
    private int screenHeight=1080;
    private boolean isOpen;

    public UsbTouchHepler(Context context){
        this.context=context;
        usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
        open(findUsbTouchDev());
        WCHUARTManager.getInstance().setUsbStateListener(new IUsbStateChange() {
            @Override
            public void usbDeviceDetach(UsbDevice device) {
                //设备移除
            }

            @Override
            public void usbDeviceAttach(UsbDevice device) {
                //设备插入
                open(findUsbTouchDev());
            }

            @Override
            public void usbDevicePermission(UsbDevice device, boolean result) {
                //请求打开设备权限结果
            }
        });
    }

    private UsbDevice findUsbTouchDev(){
        HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();
        Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
        while (deviceIterator.hasNext()) {
            usbDevice = deviceIterator.next();
            LogUtil.add("find device","VendorId="+usbDevice.getVendorId()+" ProductId="+usbDevice.getProductId()+" ProductName="+usbDevice.getProductName(),"USBHelper",false);
            if(usbManager.hasPermission(usbDevice)&&usbDevice.getProductId()==29987){
                return usbDevice;
            }
        }
        return null;
    }

    /**
     * 从设备列表中打开某个设备
     *
     * @param usbDevice
     */
    private void open( @NonNull UsbDevice usbDevice){
        if(usbDevice==null){
            ToastUtil.show(context,"未查找到USB反控设备!");
            return;
        }
        if(WCHUARTManager.getInstance().isConnected(usbDevice)){
            ToastUtil.show(context,"当前设备已经打开");
            return;
        }
        try {
            isOpen = WCHUARTManager.getInstance().openDevice(usbDevice);
            if(isOpen){
                //打开成功
                ToastUtil.show(context,"打开成功");
                //获取芯片串口数目,为负则代表出错
                int serialCount = WCHUARTManager.getInstance().getSerialCount(usbDevice);
                Log.i("luohao","serialCount="+serialCount);
                boolean bl= WCHUARTManager.getInstance().setSerialParameter(usbDevice,0,9600,8,1,0,false);
                Log.i("luohao","bl="+bl);
            }else {
                ToastUtil.show(context,"打开失败");
            }
        } catch (ChipException e) {
            LogUtil.addError(e);
        } catch (NoPermissionException e) {
            //没有权限打开该设备
            //申请权限
            ToastUtil.show(context,"没有权限打开该设备");
            requestPermission(usbDevice);
        } catch (Exception e) {
            LogUtil.addError(e);
        }
    }

    /**
     * 申请读写权限
     * @param usbDevice
     */
    private void requestPermission(@NonNull UsbDevice usbDevice){
        try {
            WCHUARTManager.getInstance().requestPermission(context,usbDevice);
        } catch (Exception e) {
            LogUtil.addError(e);
        }
    }

    //写数据
    public void writeData(@NonNull byte[] data){
        try {
            WCHUARTManager.getInstance().syncWriteData(usbDevice, 0, data,data.length,2000);
        } catch (Exception e) {
            LogUtil.addError(e);

        }
    }

    //写数据
    public void writeData(String strHex){
        if(!isOpen)return;
        try {
            byte[] data=FormatUtil.hexStringToBytes(strHex.replace(" ",""));
            int res=WCHUARTManager.getInstance().syncWriteData(usbDevice, 0, data,data.length,2000);
        } catch (Exception e) {
            LogUtil.addError(e);
        }
    }

    /**
     *按下鼠标左键
     */
    public void downMouseLeftKey(){
        writeData("57 AB 00 04 07 02 01 00 00 00 00 00 10");
    }

    /**
     *释放鼠标左键
     */
    public void upMouseLeftKey(){
        writeData("57 AB 00 04 07 02 00 00 00 00 00 00 0F");
    }

    public void clickMouseLeftKey(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    downMouseLeftKey();
                    Thread.sleep(100);
                    upMouseLeftKey();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public void moveMouse(int x,int y,boolean mouseLeftKeyDown,boolean mouseRightKeyDown){
        LogUtil.add("移动光标","x="+x+" y="+y,"反控电脑");
        int x1=( x * 4096 ) / screenWidth;
        int y1=( y * 4096 ) / screenHeight;
        String hexX=Integer.toHexString(x1);
        String hexY=Integer.toHexString(y1);

        String hexXHigh="00";
        String hexXLow="00";
        if(hexX.length()==1){
            hexXLow="0"+hexX;
        }else if(hexX.length()==2){
            hexXLow=hexX;
        }else if(hexX.length()==3){
            hexXLow=hexX.substring(1,3);
            hexXHigh="0"+hexX.substring(0,1);
        }else if(hexX.length()==4){
            hexXLow=hexX.substring(2,4);
            hexXHigh=hexX.substring(0,2);
        }

        String hexYHigh="00";
        String hexYLow="00";
        if(hexY.length()==1){
            hexYLow="0"+hexY;
        }else if(hexY.length()==2){
            hexYLow=hexY;
        }else if(hexY.length()==3){
            hexYLow=hexY.substring(1,3);
            hexYHigh="0"+hexY.substring(0,1);
        }else if(hexY.length()==4){
            hexYLow=hexY.substring(2,4);
            hexYHigh=hexY.substring(0,2);
        }
        String mouseCmd="00";
        if(mouseLeftKeyDown){
            mouseCmd="01";
        }
        if(mouseRightKeyDown){
            mouseCmd="02";
        }
        if(mouseLeftKeyDown==true&&mouseRightKeyDown==true){
            mouseCmd="03";
        }
        String cmd="57 AB 00 04 07 02 "+mouseCmd+" "+hexXLow+" "+hexXHigh+" "+hexYLow+" "+hexYHigh+" 00";

        String[] ary=cmd.split(" ");
        int sum=0;
        for(int i=0;i<ary.length;i++) {
            sum += Integer.parseInt(ary[i], 16);
        }
        String resultHex = Integer.toHexString(sum).toUpperCase();
        String lastHex="";
        if(resultHex.length()==1){
            lastHex="0"+resultHex;
        }else if(resultHex.length()==2){
            lastHex=resultHex;
        }else if(resultHex.length()==3){
            lastHex=resultHex.substring(1,3);
        }else if(resultHex.length()==4){
            lastHex=resultHex.substring(2,4);
        }
        cmd+=" "+lastHex;

        LogUtil.add("移动光标",cmd,"反控电脑");
        writeData(cmd);
    }

    public void mouseWheel(int mouseDistance){

        if(mouseDistance>0){
            mouseDistance=mouseDistance+128;
        }else{
            mouseDistance=Math.abs(mouseDistance);
        }
        String wheel=Integer.toHexString(mouseDistance).toUpperCase();
        String lastWheelHex="";
        if(wheel.length()==1){
            lastWheelHex="0"+wheel;
        }else if(wheel.length()==2){
            lastWheelHex=wheel;
        }else if(wheel.length()==3){
            lastWheelHex=wheel.substring(1,3);
        }else if(wheel.length()==4){
            lastWheelHex=wheel.substring(2,4);
        }
        String cmd="57 AB 00 04 07 02 00 00 00 00 00 "+lastWheelHex;

        String[] ary=cmd.split(" ");
        int sum=0;
        for(int i=0;i<ary.length;i++) {
            sum += Integer.parseInt(ary[i], 16);
        }
        String resultHex = Integer.toHexString(sum).toUpperCase();
        String lastHex="";
        if(resultHex.length()==1){
            lastHex="0"+resultHex;
        }else if(resultHex.length()==2){
            lastHex=resultHex;
        }else if(resultHex.length()==3){
            lastHex=resultHex.substring(1,3);
        }else if(resultHex.length()==4){
            lastHex=resultHex.substring(2,4);
        }
        cmd+=" "+lastHex;
        Log.i("luohao","mouseWheel="+cmd);
        writeData(cmd);
    }
}
